package www.com.zhongge.application;

import java.util.Stack;

/**
 * @ClassName MinStack
 * @Description TODO 最小栈
 * @Author 笨忠
 * @Date 2025/7/24 15:26
 * @Version 1.0
 */
public class MinStack {

    //首先得有两个栈
    Stack<Integer> stack;//基本栈
    Stack<Integer> minStack;//辅助栈

    public MinStack() {
        this.stack = new Stack<>();
        this.minStack = new Stack<>();
    }

    public void push(int val) {
        //基本栈都要入栈
        stack.push(val);
        //辅助栈
        if (minStack.empty()) {
            minStack.push(val);
        } else{
            if(val <= minStack.peek()){
                minStack.push(val);
            }
        }
    }

    public void pop() {
        if (stack.isEmpty()) {
            return;
        }
        //基本栈都要出栈
//        if (stack.peek() == minStack.peek()) {//出错：Integer不可以直接发生==比较
//            minStack.pop();
//            stack.pop();
//        } else {
//            stack.pop();
//        }

        //修改：
        int val = stack.peek();
        if (val ==  minStack.peek()) {//出错：Integer不可以直接发生==比较
            minStack.pop();
            stack.pop();
        } else {
            stack.pop();
        }

        //正确写法
        // int val = stack.pop();
        // if(val == minStack.peek()) {
        //     minStack.pop();
        // }
    }

    public int top() {
        //基本栈的栈顶元素
        return stack.peek();
    }

    public int getMin() {
        //得到辅助栈的栈顶元素
        return minStack.peek();
    }
}
